<!-- 中间服务情况组件 -->
<template>
  <div class="service-chart-container">
    <div
      id="serviceChartContainer"
      ref="serviceChartContainer"
      class="chart-container" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, onUnmounted } from "vue";
import * as echarts from "echarts";

const serviceChartContainer = ref<HTMLElement>();
let serviceChart: echarts.ECharts;
let resizeObserver: ResizeObserver | null = null;
const handleWindowResize = () => {
  serviceChart?.resize();
};

// 静态服务次数数据（7天）
const chartData = {
  dates: [
    "2024-10-09",
    "2024-10-10",
    "2024-10-11",
    "2024-10-12",
    "2024-10-13",
    "2024-10-14",
    "2024-10-15",
  ],
  values: [820, 932, 901, 934, 1290, 1330, 1320],
};

// 图表配置
const getChartOption = () => {
  return {
    color: ["#0052D9"],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "12%",
      top: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: chartData.dates,
      axisLabel: {
        color: "#666",
        formatter: (value: string) =>
          typeof value === "string" ? value.slice(5) : value,
      },
      axisLine: { lineStyle: { color: "#e6e6e6" } },
    },
    yAxis: {
      type: "value",
      axisLabel: { color: "#666" },
      splitLine: { lineStyle: { color: "#f0f0f0" } },
    },
    series: [
      {
        data: chartData.values,
        type: "line",
        areaStyle: {},
        smooth: true,
        lineStyle: { width: 3 },
        showSymbol: true,
      },
    ],
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "line", snap: true },
      formatter: function (params: any) {
        const date: string = params?.[0]?.axisValue;
        const value: number = params?.[0]?.value;
        return `${date}<br/>服务次数：${value}次`;
      },
    },
  };
};

// 初始化图表
const initChart = () => {
  if (serviceChartContainer.value) {
    serviceChart = echarts.init(serviceChartContainer.value);
    serviceChart.setOption(getChartOption());

    // 监听窗口大小与容器尺寸变化（解决标签页切换后不显示/尺寸为0的问题）
    window.addEventListener("resize", handleWindowResize);
    resizeObserver = new ResizeObserver(() => {
      serviceChart?.resize();
    });
    resizeObserver.observe(serviceChartContainer.value);
  }
};

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  if (serviceChart) {
    serviceChart.dispose();
  }
  window.removeEventListener("resize", handleWindowResize);
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
});
</script>

<style lang="less" scoped>
.service-chart-container {
  width: 100%;
  height: 100%;

  .chart-container {
    width: 100%;
    height: 260px;
    min-height: 260px;
  }
}
</style>
